﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;

namespace WeiXinServiceCore.Middleware
{

    /// <summary>
    /// <![CDATA[微信中间件]]>
    /// </summary>
    public class WeiXinMiddleware
    {
        /// <summary>
        ///<![CDATA[要传递的下一个中间件]]>
        /// </summary>
        private RequestDelegate Next = null;

        /// <summary>
        /// <![CDATA[配置]]>
        /// </summary>
        public IConfiguration Configuration { get; }


        /// <summary>
        /// <![CDATA[中间件配置信息]]>
        /// </summary>
        public OAuth.WeiXinServerOptions ServerOptions { get; set; }

        /// <summary>
        /// <![CDATA[构造]]>
        /// </summary>
        /// <param name="next"></param>
        /// <param name="configuration"></param>
        public WeiXinMiddleware(RequestDelegate next, IConfiguration configuration, OAuth.WeiXinServerOptions serverOptions)
        {
            Next = next;
            Configuration = configuration;
            ServerOptions = serverOptions;
        }

        /// <summary>
        /// <![CDATA[调用]]>
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path == ServerOptions.NotifyPath)
            {
                //微信服务
                if (ServerOptions.WeiXinServerProvider == null) ServerOptions.WeiXinServerProvider = (OAuth.IWeiXinServerProvider)context.RequestServices.GetService(typeof(OAuth.IWeiXinServerProvider));
                await ServerOptions.WeiXinServerProvider.Run(context, Configuration);
                return;
            }
            if (Next != null) await Next.Invoke(context);
        }
    }
}